import {DependencyList, useCallback, useEffect, useMemo} from "react";
import {HttpMethodProps, HttpParamsProps, ReqProps} from "@/common/http";
import {Form} from "antd";
import {TableActionRedux} from "@/components/ant-ext-table/redux/HAdminContext";
import {AnyParams} from "@/common/httptypes";

export function useHandle<T extends Function>(callback: T, deps: DependencyList): T {
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const handle = useCallback<T>(callback, [deps])
    useEffect(() => {
        handle?.()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    return handle
}

export function useEdit<T>(func: (props: ReqProps<T>) => void, props: HttpMethodProps<T>): Function {
    return useCallback((params?: HttpParamsProps) => {
        func({...params, ...props})
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [props])
}

export function useActionForm<SysRoleEntity>(action: TableActionRedux<SysRoleEntity>["action"], fill: string[], mapping: AnyParams<any>) {
    const [form] = Form.useForm()
    useEffect(() => {
        if (fill.indexOf(action.key) !== -1) {
            form.setFieldsValue(action.getRow())
        }
    }, [form, action, fill])
    const {key, title} = useActionTitle(action, mapping)
    return {form, key, title,}

}

export function useActionTitle<SysRoleEntity>(action: TableActionRedux<SysRoleEntity>["action"], mapping: AnyParams<any>) {
    return useMemo(() => {
        return action.getTitle(mapping)
    }, [action, mapping])

}